import BaseGroup from '@/components/js/BaseGroup'
import { EventBus } from '@/store/index'
import { getPxOVwByValue } from '@/store/utils'
export default class TurnBook extends BaseGroup {
  constructor() {
    super();
    //打组翻页动画
    this.dynamicsLoadScripts =  null
    this.interval = null
  }

  start() {
    this.interval = window.setInterval(() =>{
      if(window.$){
        clearInterval(this.interval)
        if($('.page-con').turn){
          this.initTurn(window.$)
        }else{
          const env_ = import.meta.env
          const url = env_.VITE_APP_WEB_URL + 'js/turn/turn.min.js'
          this.getTurnScript(() =>{
            this.initTurn(window.$)
          },url)
        }
      }
    },100)

    this.time = this.item.interactionData.injectJsClassObj.time
    this.nextPage =  this.item.interactionData.injectJsClassObj.nextPage
    this.onTurnBook = this.onTurnBook.bind(this);
    EventBus.$off("turnBook")
    EventBus.$on("turnBook", this.onTurnBook)
  }

  onTurnBook(){
    if(this.nextPage){
      $('.page-con').turn('next');
      window.setTimeout(() =>{
        $('.page-con').turn('destroy')
        this.showPage(this.nextPage)
      }, this.time)
    }
  }

  getTurnScript(fn,url){
    let Head = document.getElementsByTagName('head')[0];
    let linkScript = document.createElement("script");
    linkScript.type = "text/" + ("javascript");
    linkScript.src = url;
    Head.insertBefore(linkScript, Head.lastChild)
    linkScript.onload = linkScript.onerror = function() {
      if(fn) fn()
    }
  }


  changeShadow(){
    var style=".shadow{-webkit-filter: none !important;filter: none !important;}"
    var ele=document.createElement("style")
    ele.innerHTML=style
    document.getElementsByTagName('head')[0].appendChild(ele)
  }

  initTurn($) {
    let wid = getPxOVwByValue(this.item.conAttr.width * 2);
    let hei = this.item.conStyles.height;
    this.changeShadow()
    $('.page-con').turn({
      width: wid,
      height: hei,
      display: 'single',
      elevation: 50,
      acceleration: true,
    });
  }

  destroy(){
    super.destroy();
    EventBus.$off("turnBook", this.onTurnBook);
  }
}
